<?php
/*
 * @Author       : ZengHao
 * @Date         : 2024-01-04 19:47:56
 * @LastEditors  : ZengHao
 * @LastEditTime : 2024-02-03 14:55:18
 * @FilePath     : /inc/functions/el-post.php
 * @Description  : 
 * Copyright 2024 www.exehub.com, All Rights Reserved. 
 * 2024-01-04 19:47:56
 */

//获取最近发布的文章：https://www.beizigen.com/post/wordpress-get-latest-article-function-wp_get_recent_posts/
function el_get_recent_posts($count = 7, $category, $orderby = 'post_date', $order = 'DESC')
{
    $args = array(
        'numberposts' => $count,
        'offset' => 0,
        'category' => $category,
        'orderby' => $orderby,
        'order' => $order,
        'post_type' => 'post',
        'post_status' => 'publish',
        'suppress_filters' => true
    );
    $post = wp_get_recent_posts($args);
    return $post;
}

//注册阅读量
function el_post_views_record()
{
    $post_id = !empty($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
    if ($post_id) {
        $post_views = (int) get_post_meta($post_id, 'views', true);
        $new = $post_views + 1;
        update_post_meta($post_id, 'views', $new);
        // 查询term的阅读量总和
        $term_views_objs = el_get_term_post_views_objs($post_id);
        if ($term_views_objs) {
            foreach ($term_views_objs as $term) {
                ECache::set($term->id, $term->views);
                // wp_cache_set($term->id, $term->views, 'term_views_count');
                update_term_meta($term->id, 'views', $term->views);
                // get_ancestors: 这个函数返回一个给定对象（文章、页面等）的祖先ID的数组
                $ancestors = get_ancestors($term->id, $term->taxonomy, 'taxonomy');
                if ($ancestors) {
                    foreach ($ancestors as $ancestors_id) {
                        //获取分类全部文章的阅读总和
                        $count = el_get_term_posts_meta_sum($ancestors_id, 'views');
                        ECache::set($ancestors_id, $count);
                        // wp_cache_set($ancestors_id, $count, 'term_views_count');
                        update_term_meta($ancestors_id, 'views', $count);
                        $term_views_objs[] = array(
                            'id' => $ancestors_id,
                            'views' => $count,
                            'taxonomy' => $term->taxonomy,
                            'is_parent ' => true,
                        );
                    }
                }
            }
        }

        do_action('posts_views_record', $post_id, $new);
        wp_send_json_success(array('post_id' => $post_id, 'views' => $new, 'term' => $term_views_objs, 'num_queries' => get_num_queries(), 'timer_stop' => timer_stop(0, 6) * 1000 . 'ms'));
    }
    wp_send_json_error(array('error' => '阅读量记录失败'));
}
add_action('wp_ajax_views_record', 'el_post_views_record');
add_action('wp_ajax_nopriv_views_record', 'el_post_views_record');

/**
 * @description: 查询term的阅读量总和
 * @param {*} $post_id
 * @return {*}
 */
function el_get_term_post_views_objs($post_id)
{

    global $wpdb;
    $sql_postmeta = $wpdb->postmeta;
    $sql_posts = $wpdb->posts;
    $sql_term_rel = $wpdb->term_relationships;
    $sql_taxonomy = $wpdb->term_taxonomy;

    $sql = "SELECT $sql_taxonomy.term_id as id,$sql_taxonomy.taxonomy as taxonomy,SUM($sql_postmeta.meta_value) as views FROM $sql_postmeta
    INNER JOIN $sql_term_rel ON $sql_term_rel.term_taxonomy_id in (SELECT term_taxonomy_id FROM $sql_term_rel WHERE $sql_term_rel.object_id = $post_id )
    INNER JOIN $sql_taxonomy ON $sql_taxonomy.term_taxonomy_id = $sql_term_rel.term_taxonomy_id
    INNER JOIN $sql_posts ON $sql_posts.ID = $sql_term_rel.object_id AND $sql_posts.post_status = 'publish'
    WHERE $sql_term_rel.object_id = $sql_postmeta.post_id and $sql_postmeta.meta_key = 'views'
    GROUP BY $sql_taxonomy.term_id";

    $query = $wpdb->get_results($sql);
    return $query;
}

//获取分类全部文章的阅读总和
function el_get_term_posts_meta_sum($term_id, $mata)
{
    $term_obj = get_term($term_id);
    if (!isset($term_obj->term_id)) {
        return 0;
    }

    $term_id = $term_obj->term_id;
    global $wpdb;
    $cache_num = ECache::get($term_id, 'term_posts_' . $mata . '_count');
    // $cache_num = wp_cache_get($term_id, 'term_posts_' . $mata . '_count', true);
    if ($cache_num === false) {
        $term_id_sql = " = $term_id";

        $children = get_term_children($term_id, $term_obj->taxonomy);
        if ($children) {
            $children[] = $term_id;
            $tt = implode(',', $children);
            $term_id_sql = " IN ($tt)";
        }

        $num = $wpdb->get_var("SELECT sum(meta_value) FROM $wpdb->posts
        LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
        INNER JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )
        INNER JOIN $wpdb->term_taxonomy ON ( $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id )
        WHERE ( $wpdb->postmeta.meta_key = '$mata')
        AND ($wpdb->posts.post_type = 'post')
        AND ($wpdb->posts.post_status = 'publish')
        AND ( $wpdb->term_taxonomy.term_id $term_id_sql)");
        //添加缓存，12小时有效
        // wp_cache_set($term_id, $num, 'term_posts_' . $mata . '_count', 43200);
        ECache::set($term_id, $num, 'term_posts_' . $mata . '_count', 43200);
    } else {
        $num = $cache_num;
    }

    return $num;
}

/**
 * @description: 获取term的总查看量
 * @param {*} $term_id
 * @return {*}
 */
function el_get_term_post_views_sum($term_id, $is_cut = false)
{
    if (!$term_id) {
        $term_id = get_queried_object_id();
    }

    //第一步通过缓存获取
    // $cache_num = wp_cache_get($term_id, 'term_views_count', true);
    $cache_num = ECache::get($term_id);
    if (false !== $cache_num) {
        return _cut_count($cache_num);
    }

    $count = get_term_meta($term_id, 'views', true);

    return $is_cut ? _cut_count($count) : (int) $count;
}

function get_post_view_count($before = '阅读[', $after = ']', $post_id = 0)
{
    if (!$post_id) {
        global $post;
        $post_id = $post->ID;
    }
    $views = _cut_count(get_post_meta($post_id, 'views', true));
    return $before . $views . $after;
}

function _cut_count($number)
{
    $number = (float) $number;
    if ($number > 999999) {
        return round($number / 10000, 0) . 'W+';
    }
    if ($number > 9999) {
        return round($number / 10000, 1) . 'W+';
    }
    return $number;
}

/**
 * @description: 主-获取文章缩略图
 * @param {*}
 * @return {*}
 */
function el_post_thumbnail($size = '', $class = 'fit-cover', $show_url = true, $post = null)
{
    if (!$size) {
        $size = _opz('thumb_postfirstimg_size');
    }

    if (!is_object($post)) {
        $post = get_post($post);
    }

    //查询缓存
    $cache_url = wp_cache_get($post->ID, 'post_thumbnail_url_' . $size, true);
    if (false === $cache_url) {
        $img_url = '';

        //特色图像
        $post_thumbnail_id = get_post_thumbnail_id($post->ID); //特色图像
        if ($post_thumbnail_id) {
            $image_src = el_get_attachment_image_src($post_thumbnail_id, $size);
            $img_url = isset($image_src[0]) ? $image_src[0] : '';
        }

        //外链特色图像
        if (!$img_url) {
            $img_url = get_post_meta($post->ID, 'thumbnail_url', true);
        }

        //文章首图
        if (!$img_url && _opz('thumb_postfirstimg_s', false)) {
            $post_img_urls = el_get_post_img_urls($post);
            $img_url = isset($post_img_urls[0]) ? $post_img_urls[0] : '';

            if ($img_url && ($size && 'full' !== $size)) {
                $img_id = el_get_image_id($img_url);
                if ($img_id) {
                    $img = wp_get_attachment_image_src($img_id, $size);
                    if (isset($img[0])) {
                        $img_url = $img[0];
                    }
                }
            }
        }

        //分类图
        if (!$img_url && _opz('thumb_catimg_s', false)) {
            $category = get_the_category();
            foreach ($category as $cat) {
                $img_url = el_get_taxonomy_img_url($cat->cat_ID, $size);
                if ($img_url) {
                    break;
                }
            }
        }

        wp_cache_set($post->ID, $img_url, 'post_thumbnail_url_' . $size);
    } else {
        $img_url = 'no' == $cache_url ? '' : $cache_url;
    }

    //输出链接
    if ($show_url) {
        return $img_url;
    }

    // $lazy_thumb = el_get_lazy_thumb();
    // $r_attr     = '';
    // $alt        = $post->post_title . el_get_delimiter_blog_name();
    // if (!$img_url) {
    //     $img_url = el_get_spare_thumb();
    //     $r_attr  = ' data-thumb="default"';
    // }

    // if (el_is_lazy('lazy_posts_thumb')) {
    //     return sprintf('<img' . $r_attr . ' src="%s" data-src="%s" alt="%s" class="lazyload ' . $class . '">', $lazy_thumb, $img_url, $alt);
    // } else {
    //     return sprintf('<img' . $r_attr . ' src="%s" alt="%s" class="' . $class . '">', $img_url, $alt);
    // }
}

function el_get_attachment_image_src($img_id, $size = false)
{
    $url = '';
    if (!$size || 'full' == $size) {
        $file = get_post_meta($img_id, '_wp_attached_file', true);
        if ($file) {
            // Get upload directory.
            $uploads = wp_get_upload_dir();
            if ($uploads && false === $uploads['error']) {
                // Check that the upload base exists in the file location.
                if (0 === strpos($file, $uploads['basedir'])) {
                    // Replace file location with url location.
                    $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file);
                } elseif (false !== strpos($file, 'wp-content/uploads')) {
                    // Get the directory name relative to the basedir (back compat for pre-2.7 uploads).
                    $url = trailingslashit($uploads['baseurl'] . '/' . _wp_get_attachment_relative_path($file)) . wp_basename($file);
                } else {
                    // It's a newly-uploaded file, therefore $file is relative to the basedir.
                    $url = $uploads['baseurl'] . "/$file";
                }
            }
        }
        if (empty($url)) {
            $url = get_the_guid($img_id);
        }
        return array($url, 0, 0);
    } else {
        return wp_get_attachment_image_src($img_id, $size);
    }
}

//列表多图模式获取文章图片
function el_posts_multi_thumbnail($post)
{
    if (!is_object($post)) {
        $post = get_post($post);
    }

    $cache_html = wp_cache_get($post->ID, 'post_multi_thumbnail', true);
    if (false === $cache_html) {
        $class = 'fit-cover radius8';
        $html = el_get_post_imgs($post, _opz('thumb_postfirstimg_size'), $class, 4, true);
        if (el_is_lazy('lazy_posts_thumb')) {
            $html = str_replace(' src=', ' src="' . el_get_lazy_thumb() . '" data-original=', $html);
            $html = str_replace(' class="', ' class="lazyload ', $html);
        }
        wp_cache_set($post->ID, $html, 'post_multi_thumbnail');
    } else {
        $html = $cache_html;
    }
    return $html;
}

/**
 * @description: 获取文章内的图片
 * @param {*}
 * @return {*}
 */
function el_get_post_imgs($post = null, $size = '', $class = '', $count = 4, $show_badge = false)
{
    $images = el_get_post_img_urls($post);
    $html = '';
    $i = 0;
    $alt = $post->post_title . el_get_delimiter_blog_name();

    foreach ($images as $src) {

        if ($size && 'full' != $size) {
            $img_id = el_get_image_id($src);
            if ($img_id) {
                $img = wp_get_attachment_image_src($img_id, $size);
                if (isset($img[0])) {
                    $src = $img[0];
                }
            }
        }

        if ($count && $i == $count - 1) {
            $badge = '';
            if ($show_badge) {
                $count_surplus = count($images) - $count; //剩余数量
                $badge = $count_surplus ? '<div class="abs-center right-top"><badge class="b-black mr6 mt6 em09"><i class="fa fa-image mr3" aria-hidden="true"></i>+' . $count_surplus . '</badge></div>' : '';
            }
            $html .= '<span>' . $badge . '<img data-original="' . $src . '" src="' . esc_url(LAZY_COVER) . '" class="lazyload ' . $class . '" alt="' . esc_attr(strip_tags($alt)) . '"></span>';
            break;
        } else {
            $html .= '<span><img data-original="' . $src . '" src="' . esc_url(LAZY_COVER) . '" class="lazyload ' . $class . '" alt="' . esc_attr(strip_tags($alt)) . '"></span>';
        }

        $i++;
    }

    return $html;
}

//获取文章中的图片数量
function el_get_post_imgs_count($post)
{
    return count((array) el_get_post_img_urls($post));
}

//从文章中获取图片数组
function el_get_post_img_urls($post = null)
{
    if (!is_object($post)) {
        $post = get_post($post);
    }

    //静态变量
    static $post_content_img = array();

    if (!isset($post_content_img[$post->ID])) {
        $content = strip_shortcodes($post->post_content); //删除短代码

        preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
        $images = $strResult[1] ? $strResult[1] : array();
        $post_content_img[$post->ID] = $images;
    } else {
        $images = $post_content_img[$post->ID];
    }

    return $images;
}

function el_posts_list($args = array(), $new_query = false, $echo = true)
{

    $defaults = array(
        'type' => 'auto',
        'no_author' => false,
        'is_mult_thumb' => false,
        'is_no_thumb' => false,
        'is_category' => is_category(),
        'is_search' => is_search(),
        'is_home' => is_home(),
        'is_author' => is_author(),
        'is_tag' => is_tag(),
        'is_topics' => is_tax('topics'),
    );

    $args = wp_parse_args((array) $args, $defaults);

    $html = '';
    if ($new_query) {
        while ($new_query->have_posts()):
            $new_query->the_post();
            $html .= el_mian_posts_while($args, false);
        endwhile;
    } else {
        while (have_posts()):
            the_post();
            $html .= el_mian_posts_while($args, false);
        endwhile;
    }

    if (!$html) {
        $html = el_get_ajax_null('暂无内容', '100', 'null-post.svg');
    }

    if ($echo) {
        echo $html;
    } else {
        return $html;
    }

    wp_reset_query();
}


function el_mian_posts_while($args = array(), $echo = true)
{
    $defaults = array(
        'type' => 'auto',
        'no_author' => false,
        'is_mult_thumb' => false,
        'is_no_thumb' => false,
        'is_category' => false,
        'is_search' => false,
        'is_home' => false,
        'is_author' => false,
        'is_tag' => false,
        'is_topics' => false,
    );

    if ($args['is_author']) {
        $args['no_author'] = true;
    }

    $args = wp_parse_args((array) $args, $defaults);

    // TODO:增加对文章显示类型的判断
    // 首页
    if($args['is_home']){
        $home_list_type = _opz('home_list_type',1);
        if($home_list_type == 0){
            $ransNum = rand(1,2);
            switch ($ransNum) {
                case 1:
                    $html = el_posts_mian_list_list($args);
                    break;
                case 2:
                    $html = el_posts_mian_list_cover($args);
                    break;
                default:
                    $html = el_posts_mian_list_list($args);
                    break;
            }
        }
        if ($home_list_type == 1) {
            $html = el_posts_mian_list_list($args);
        }
        if ($home_list_type == 2) {
            $html = el_posts_mian_list_card($args);
        }
        if ($home_list_type == 3) {
            $html = el_posts_mian_list_cover($args);
        }
    }

    if($args['is_category']){
        $cat_list_type = _opz('cat_list_type',1);
        if($cat_list_type == 0){
            $ransNum = rand(1,2);
            switch ($ransNum) {
                case 1:
                    $html = el_posts_mian_list_list($args);
                    break;
                case 2:
                    $html = el_posts_mian_list_cover($args);
                    break;
                default:
                    $html = el_posts_mian_list_list($args);
                    break;
            }
        }
        if ($cat_list_type == 1) {
            $html = el_posts_mian_list_list($args);
        }
        if ($cat_list_type == '2') {
            $html = el_posts_mian_list_card($args);
        }
        if ($cat_list_type == 3) {
            $html = el_posts_mian_list_cover($args);
        }
    }

    if($args['is_tag']){
        $tag_list_type = _opz('tag_list_type',1);
        if($tag_list_type == 0){
            $ransNum = rand(1,2);
            switch ($ransNum) {
                case 1:
                    $html = el_posts_mian_list_list($args);
                    break;
                case 2:
                    $html = el_posts_mian_list_cover($args);
                    break;
                default:
                    $html = el_posts_mian_list_list($args);
                    break;
            }
        }
        if ($tag_list_type == 1) {
            $html = el_posts_mian_list_list($args);
        }
        if ($tag_list_type == 2) {
            $html = el_posts_mian_list_card($args);
        }
        if ($tag_list_type == 3) {
            $html = el_posts_mian_list_cover($args);
        }
    }

    if($args['is_search']){
        $search_list_type = _opz('search_list_type',1);
        if($search_list_type == 0){
            $ransNum = rand(1,2);
            switch ($ransNum) {
                case 1:
                    $html = el_posts_mian_list_list($args);
                    break;
                case 2:
                    $html = el_posts_mian_list_cover($args);
                    break;
                default:
                    $html = el_posts_mian_list_list($args);
                    break;
            }
        }
        if ($search_list_type == 1) {
            $html = el_posts_mian_list_list($args);
        }
        if ($search_list_type == 2) {
            $html = el_posts_mian_list_card($args);
        }
        if ($search_list_type == 3) {
            $html = el_posts_mian_list_cover($args);
        }
    }

    if ($echo) {
        echo $html;
    } else {
        return $html;
    }
}

function iscard($page = 'home'){
   $is_card =  _opz($page.'_list_type') == 2;
   if ($is_card) {
    return 'iscard';
   }else{
    return '';
   }
}

//文章多重筛选代码
//通过pre_get_posts钩子筛选
add_action('pre_get_posts', 'el_sift_posts_per_page', 999);
function el_sift_posts_per_page($query)
{
    //is_category()即为分类页面有效，自行更换。
    //$query->is_main_query()使得仅对默认的页面主查询有效
    //!is_admin()避免影响后台文章列表

    if ((is_category() || is_tag() || is_home() || is_tax('topics')) && $query->is_main_query() && !is_admin()) {
        // 分类
        if (isset($_GET['cat'])) {
            $cat = $_GET['cat'];
            $query->set('cat', $cat);
        }
        //  标签
        if (isset($_GET['tag'])) {
            $tag = $_GET['tag'];
            $query->set('tag', $tag);
        }
        // 自定义分类法：taxonomy  topics
        if (isset($_GET['topics'])) {
            $array_temp = array(array('taxonomy' => 'topics', 'terms' => preg_split("/,|，|\s|\n/", $_GET['topics'])));
            $query->set('tax_query', $array_temp);
        }

        // 自定义字段：mate type
        if (isset($_GET['type'])) {
            $array_temp = array('key' => 'type', 'value' => $_GET['type'], 'compare' => '=');
        }

        $filter_args = el_get_custom_filter_args();
        foreach ($filter_args as $filters) {

            if (!empty($_GET[$filters['key']])) {

                $meta_query = $query->get('meta_query');

                $filters_meta_query = array(
                    'key'     => $filters['key'],
                    'value'   => esc_sql($_GET[$filters['key']]),
                    'compare' => 'LIKE',
                );

                $meta_query   = is_array($meta_query) ? $meta_query : array();
                $meta_query[] = $filters_meta_query;

                $query->set('meta_query', $meta_query);
            }
        }
    }
}
function el_get_custom_filter_args()
{
    $opts        = _opz('custom_filter');
    $filter_args = array();
    if ($opts && is_array($opts)) {
        foreach ($opts as $opt) {
            if ($opt['key']) {
                $options = array();
                foreach ($opt['vals'] as $val) {
                    if ($val['key']) {
                        $name                 = $val['name'] ?: $val['key'];
                        $options[$val['key']] = $name;
                    }
                }

                if ($options) {
                    $filter_args[] = array(
                        'key'  => $opt['key'],
                        'name' => $opt['name'] ?: $opt['key'],
                        'vals' => $options,
                    );
                }
            }
        }
    }
    return $filter_args;
}

//文章排序
//通过pre_get_posts钩子筛选
add_action('pre_get_posts', 'el_sift_posts_per_orde', 9999);
function el_sift_posts_per_orde($query)
{
    //正反顺序
    if (isset($_GET['order']) && $query->is_main_query() && !is_admin()) {
        $order = 'DESC' == $_GET['order'] ? 'DESC' : 'ASC';
        $query->set('order', $order);
    }
    //按照什么排序
    if (isset($_GET['orderby']) && $query->is_main_query() && !is_admin()) {
        $orderby           = $_GET['orderby'];
        $orderby_keys      = el_get_query_mate_orderby_keys();
        $mate_orderbys     = $orderby_keys['value'];
        $mate_orderbys_num = $orderby_keys['value_num'];

        if (in_array($orderby, $mate_orderbys_num)) {
            $query->set('orderby', 'meta_value_num');
            $query->set('meta_key', $orderby);
        } elseif (in_array($orderby, $mate_orderbys)) {
            $query->set('orderby', 'meta_value');
            $query->set('meta_key', $orderby);
        } else {
            $query->set('orderby', $orderby);
        }
    }

    //帖子状态
    global $wp_query;
    $curauth = $wp_query->get_queried_object();

    if (isset($_GET['post_status']) && $query->is_main_query() && (is_super_admin() || (!empty($curauth->ID) && get_current_user_id() === $curauth->ID))) {
        $query->set('post_status', $_GET['post_status']);
    }
}

/**
 * @description: 过滤new WP_Query orderby的args
 * @param {*} $orderby
 * @param {*} $args
 * @return {*}
 */
function el_query_orderby_filter($orderby, $args = array())
{

    $orderby_keys      = el_get_query_mate_orderby_keys();
    $mate_orderbys     = $orderby_keys['value'];
    $mate_orderbys_num = $orderby_keys['value_num'];

    if (in_array($orderby, $mate_orderbys_num)) {
        $args['orderby']  = 'meta_value_num';
        $args['meta_key'] = $orderby;
    } elseif (in_array($orderby, $mate_orderbys)) {
        $args['orderby']  = 'meta_value';
        $args['meta_key'] = $orderby;
    } else {
        $args['orderby'] = $orderby;
    }

    if (!isset($args['order'])) {
        $args['order'] = 'DESC';
    }

    return $args;
}

function el_get_query_mate_orderby_keys()
{
    return apply_filters('query_mate_orderby_keys', array(
        'value_num' => array('score', 'plate_id', 'posts_count', 'reply_count', 'today_reply_count', 'follow_count', 'follow', 'views', 'like', 'favorite', 'zibpay_price', 'zibpay_points_price', 'sales_volume', 'balance', 'points', 'phone_number', 'vip_level', 'level', 'referrer_id'),
        'value'     => array('last_reply', 'last_post', 'last_login'),
    ));
}



function el_posts_mian_list_cover($args){
    $defaults = array(
        'type' => 'auto',
        'no_author' => false,
        'is_mult_thumb' => false,
        'is_no_thumb' => false,
        'is_category' => false,
        'is_search' => false,
        'is_home' => false,
        'is_author' => false,
        'is_tag' => false,
        'is_topics' => false,
    );

    $args = wp_parse_args((array) $args, $defaults);
    $post_cover = el_get_posts_cover('item-img-inner','cover'); // 文章封面
    $title = el_get_post_title(); // 文章标题
    $excerpt = el_get_post_excerpt(200); // 文章摘要
    // $taxonomy = el_get_post_taxonomy(); //文章标签，分类信息
    $meta = el_get_posts_list_meta(); // 文章meta
    $html = '';
    $html .= '<li class="post-item-cover panel-picture "><div class="item-in">' . $post_cover;
    $html .= '<div class="item-content">' . $title . $excerpt . $meta;
    $html .= '</div></li>';
    return $html;
}

function el_posts_mian_list_card($args)
{
    $defaults = array(
        'type' => 'auto',
        'no_author' => false,
        'is_mult_thumb' => false,
        'is_no_thumb' => false,
        'is_category' => false,
        'is_search' => false,
        'is_home' => false,
        'is_author' => false,
        'is_tag' => false,
        'is_topics' => false,
    );

    $args = wp_parse_args((array) $args, $defaults);
    // 文章的信息准备
    /**
     * 1.文章标题+文章的概要
     * 2.文章阅读量、点赞量、评论量等
     * 3、文章的作者头像和链接
     * 4、文章的发布时间
     * 5、文章的封面
     */
    $post_cover = el_get_posts_cover('item-img-inner',true); // 文章封面
    $title = el_get_post_title(); // 文章标题
    $excerpt = el_get_post_excerpt(); // 文章摘要
    // $taxonomy = el_get_post_taxonomy(); //文章标签，分类信息
    $meta = el_get_posts_card_meta(); // 文章meta
    $html = '';

    $html .= '<li class="post-item-card"><div class="item-in">' . $post_cover;
    $html .= '<div class="item-content">' . $title . $excerpt . $meta;
    $html .= '</div></li>';
    return $html;
}

function el_posts_mian_list_list($args)
{
    $defaults = array(
        'type' => 'auto',
        'no_author' => false,
        'is_mult_thumb' => false,
        'is_no_thumb' => false,
        'is_category' => false,
        'is_search' => false,
        'is_home' => false,
        'is_author' => false,
        'is_tag' => false,
        'is_topics' => false,
    );

    $args = wp_parse_args((array) $args, $defaults);
    // 文章的信息准备
    /**
     * 1.文章标题+文章的概要
     * 2.文章阅读量、点赞量、评论量等
     * 3、文章的作者头像和链接
     * 4、文章的发布时间
     * 5、文章的封面
     */
    $post_cover = el_get_posts_cover(); // 文章封面
    $title = el_get_post_title(); // 文章标题
    $excerpt = el_get_post_excerpt(); // 文章摘要
    // $taxonomy = el_get_post_taxonomy(); //文章标签，分类信息
    $meta = el_get_posts_list_meta(); // 文章meta
    $html = '';

    $html .= '<li class="post-item">' . $post_cover;
    $html .= '<div class="item-content">' . $title . $excerpt . $meta;
    $html .= '</li>';
    return $html;
}

function el_get_post_title($class = 'item-title')
{
    $get_permalink = get_permalink();
    $target_blank = _opz('target_blank') ? ' target="_blank"' : '';
    $title = get_the_title();
    if (is_sticky()) {
        $html = '<h2 class="' . $class . '"><a ' . $target_blank . ' href="' . esc_url($get_permalink) . '" title="' . $title . '" rel="bookmark"><span class="sticky-badge">置顶</span>' . $title . '</a></h2>';
    } else {
        $html = '<h2 class="' . $class . '"><a ' . $target_blank . ' href="' . esc_url($get_permalink) . '" title="' . $title . '" rel="bookmark">' . $title . '</a></h2>';
    }
    return $html;
}

//获取文章列表的图片
function el_get_posts_cover($class = 'item-img-inner',$type = 'list')
{
    global $post;
    // 定义需要的参数数组
    $post_args = array(
        'permalink' => '',
        'post_title' => '',
        'target_blank' => '',
        'thumb' => '',
        'categories' => '',
    );
    $def_layz_cover = _opz('lazyload_def_cover');
    // 缓存获取数据，如果获取不到，再进行查询
    $post_args = ECache::get('post_list_cover_' . $post->ID);
    if (false === $post_args) {
        $permalink = get_permalink();
        $post_title = get_the_title();
        $target_blank = _opz('target_blank') ? ' target="_blank"' : '';
        $thumb = el_post_thumbnail('', 'fit-cover radius8');
        $categories = get_the_category(); // 可能是数组
        $post_args['permalink'] = $permalink;
        $post_args['post_title'] = $post_title;
        $post_args['target_blank'] = $target_blank;
        $post_args['thumb'] = $thumb;
        $post_args['categories'] = $categories;
        ECache::set('post_list_cover_' . $post->ID, $post_args, EL_CACHE, DAY_IN_SECONDS);
    }

    $cat_html = '';
    if (is_sticky()) {
        $cat_html .= '<a class="item-category sticky" href="" target="_blank">置顶</a>';
    } else {
        if (!empty($post_args['categories'][0])) {
            $cat_i = 0;
            foreach ($post_args['categories'] as $category) {
                // 获取分类的链接
                if ($cat_i < 1) {
                    $category_link = get_category_link($category->term_id);
                    $cat_html .= '<a class="item-category" href="' . esc_url($category_link) . '" target="_blank">' . $category->name . '</a>';
                }
                $cat_i++;
            }
        }
    }
    if ($type == 'card') {
        $cat_html = '';
    }
    $html = '<div class="item-img"><a class="' . $class . '" href="' . esc_url($post_args['permalink']) . '" title="' . $post_args['post_title'] . '" ' . $post_args['target_blank'] . ' rel="bookmark"><img class="post-cover lazyload" data-original="' . esc_url($post_args['thumb']) . '" src="' . $def_layz_cover . '" alt="' . $post_args['post_title'] . '"></a>' . $cat_html . '</div>';
    return $html;
}

function el_get_post_taxonomy($cat_class = "c-blue", $tag_class = "", $show_cat = true, $show_tag = false, $post = null)
{
    if (!is_object($post)) {
        $post = get_post($post);
    }
    if (!isset($post->ID)) {
        return;
    }
    if (_opz('show_post_cat')) {
        $show_cat = true;
    }
    if (_opz('show_post_tag')) {
        $show_tag = true;
    }
    $categories = get_the_category();
    $tags = get_the_tags();
    $taxonomy_html = '';
    if ($show_cat && !empty($categories)) {
        $cat_i = 0;
        foreach ($categories as $category) {
            if ($cat_i < 2) {
                $taxonomy_html .= '<a class="but ' . $cat_class . '" target="_blank" title="查看分类：' . $category->name . '下的更多文章" href="' . esc_url(get_category_link($category->term_id)) . '"><i class="fa fa-folder-open-o" aria-hidden="true"></i>' . $category->name . '</a>';
                $cat_i++;
            }
        }
    }
    if ($show_tag && !empty($tags)) {
        $tag_i = 0;
        foreach ($tags as $tag) {
            if ($tag_i < 4) {
                $taxonomy_html .= '<a href="' . esc_url(get_tag_link($tag->term_id)) . '" title="查看标签：' . $tag->name . '下的更多文章" class="but"># ' . $tag->name . '</a>';
            }
            $tag_i++;
        }
    }

    return '<div class="item-taxonomy">' . $taxonomy_html . '</div>';
}

function el_get_posts_card_meta($show_author = true, $is_card = true, $post = null)
{
    if (!is_object($post)) {
        $post = get_post($post);
    }
    if (!isset($post->ID)) {
        return;
    }

    if (_opz('list_orderby') == 'modified') {
        $time = get_the_modified_time('Y-m-d H:i:s', $post);
    } else {
        $time = get_the_time('Y-m-d H:i:s', $post);
    }
    $time_ago = el_get_time_ago($time);
    $meta_time = '<item title="' . esc_attr($time) . '" class="item-meta-li date">' . $time_ago . '</item>';
    
    if ($show_author) {

        $author_name = '';
        $author_id = $post->post_author;
        $user = get_userdata($author_id);
        if (!$is_card) {
            if (isset($user->display_name)) {
                $author_name = '<span class="hide-sm ml6">' . $user->display_name . '</span>';
            }
        }
        $author_name = '<span class="hide-sm ml6">' . $user->display_name . '</span>';
        // $author    = el_get_avatar_box($author_id, 'avatar-mini') . $author_name;
        $author_url = el_get_user_home_url($author_id);
        $author_img = el_get_data_avatar($author_id);
        $author = ' <a target="_blank" href="' . esc_url($author_url) . '" class="avatar-box j-user-card">' . $author_img . $author_name . '</a>';
        $meta_left = '<div class="item-meta-li author">' . $author . '</div>' . $meta_time;
    } else {
        $meta_left = $meta_time;
    }

    $meta_top = '<div class="post-list-meta-box">';
    $meta_top .= el_get_post_taxonomy();
    $meta_top .= '<div class="post-meta">'.el_get_posts_meta($post).'</div>';
    
    $meta_top .= '</div>';

    $html = $meta_top;
    $html .= '<div class="list-footer">';
    $html .= $meta_left;
    $html .= '</div>';
    return $html;
}

//获取文章列表的底部meta
function el_get_posts_list_meta($show_author = true, $is_card = false, $post = null)
{
    if (!is_object($post)) {
        $post = get_post($post);
    }
    if (!isset($post->ID)) {
        return;
    }

    if (_opz('list_orderby') == 'modified') {
        $time = get_the_modified_time('Y-m-d H:i:s', $post);
    } else {
        $time = get_the_time('Y-m-d H:i:s', $post);
    }
    $time_ago = el_get_time_ago($time);
    //  && _opz('post_list_author')
    $meta_time = '<item title="' . esc_attr($time) . '" class="item-meta-li date">' . $time_ago . '</item>';
    if ($show_author) {

        $author_name = '';
        $author_id = $post->post_author;
        $user = get_userdata($author_id);
        if (!$is_card) {
            if (isset($user->display_name)) {
                $author_name = '<span class="hide-sm ml6">' . $user->display_name . '</span>';
            }
        }
        $author_name = '<span class="hide-sm ml6">' . $user->display_name . '</span>';
        // $author    = el_get_avatar_box($author_id, 'avatar-mini') . $author_name;
        $author_url = el_get_user_home_url($author_id);
        $author_img = el_get_data_avatar($author_id);
        $author = ' <a target="_blank" href="' . esc_url($author_url) . '" class="avatar j-user-card">' . $author_img . $author_name . '</a>';
        $meta_left = '<div class="item-meta-li author">' . $author . '</div>' . $meta_time;
    } else {
        $meta_left = $meta_time;
    }

    $meta_right = '<div class="item-meta-right">' . el_get_posts_meta($post) . '</div>';

    $html = '<div class="item-meta">';
    $html .= $meta_left;
    $html .= $meta_right;
    $html .= '</div>';
    return $html;
}
function el_excerpt_more($more)
{
    return ' ...';
}
add_filter('excerpt_more', 'el_excerpt_more');

// 获取摘要
function el_get_post_excerpt($limit = 90, $html = true, $post = null)
{
    if (!$post)
        $post = get_post();

    $post_excerpt = ECache::get('post_excerpt_' . $post->ID);
    if (false === $post_excerpt) {
        $post_excerpt = $post->post_excerpt;
        if ($post_excerpt == '') {
            $post_content = $post->post_content;
            $post_content = do_shortcode($post_content);
            $post_content = wp_strip_all_tags($post_content);

            $post_excerpt = mb_strimwidth($post_content, 0, $limit, '…', 'utf-8');
        }
        ECache::set('post_excerpt_' . $post->ID, $post_excerpt);
    }
    $post_excerpt = wp_strip_all_tags($post_excerpt);
    $post_excerpt = trim(preg_replace("/[\n\r\t ]+/", ' ', $post_excerpt), ' ');
    if ($html) {
        return '<div class="item-excerpt"><p>' . $post_excerpt . '</p></div>';
    } else {
        return $post_excerpt;
    }
}

// 获取文章meta标签
function el_get_posts_meta($post = null)
{

    if (!is_object($post)) {
        $post = get_post($post);
    }
    $post_id = $post->ID;

    $meta = '';
    $comment_href = '';
    $is_single = is_single($post);
    // 阅读量
    $meta .= '<span class="item-meta-li views" title="阅读数"><i data-feather="eye"></i> ' . get_post_view_count('', '', $post_id) . '</span>';
    if (comments_open($post) && !_opz('close_comments')) {
        if ($is_single) {
            $comment_href = 'javascript:(scrollTo(\'#comments\',-50));';
        } else {
            $comment_href = get_comments_link($post_id);
        }
        // 评论数
        $meta .= '<a class="item-meta-li" data-toggle="tooltip" title="去评论" href="' . $comment_href . '"><i data-feather="message-square"></i> ' . get_comments_number($post_id) . '</a>';

    }
    if (_opz('post_like_s', true) && $post->post_type == 'post') {
        // 收藏数
        $meta .= '<span class="item-meta-li stars" title="收藏数"><i data-feather="star"></i> '.get_post_favorites($post).'</span>';
        // 点赞数
        $meta .= '<span class="item-meta-li likes" title="点赞数"><i data-feather="thumbs-up"></i> ' . get_post_likes($post) . '</span>';
        // $meta .= '<item class="meta-like">' . el_get_svg('like') . (el_get_post_like('', $post_id, '', true) ?: '0') . '</item>';
    }
    return $meta;
}


function el_ajax_post_tabs($page = 'home', $attr = 'win-ajax-replace="filter"')
{
    if (!empty($_GET['nofilter'])) {
        return;
    }
    $page_args = array();
    if ($page == 'home') {
        $page_args['home'] = array(
            'cat' => false,
            'cat_option' => false,
            'topics' => false,
            'topics_option' => false,
            'tag' => false,
            'custom' => false,
            'tag_option' => false,
            'orderby' => _opz('home_list1_orderby_s'),
            'orderby_option' => _opz('home_list1_orderby_option'),
        );
    }
    $html ='';
    $html .= '<section class="el-widget mb-3 ">'.el_widget_title('文章列表');

    $html .= '<div class="post-opt-list">';
    $html .= '<div class="opt-list-row">';
    $html .= '<a href="'.esc_url(home_url( '/' )).'?orderby=all" class="opt-item picked"><span data-opt="all">全部</span></a>';
    $html .= '<a href="'.esc_url(home_url( '/' )).'?orderby=update" class="opt-item"><span data-opt="update">更新</span></a>';
    $html .= '<a href="'.esc_url(home_url( '/' )).'?orderby=view" class="opt-item"><span data-opt="views">浏览</span></a>';
    $html .= '<a href="'.esc_url(home_url( '/' )).'?orderby=like" class="opt-item"><span data-opt="likes">点赞</span></a>';
    $html .= '<a href="'.esc_url(home_url( '/' )).'?orderby=favorite" class="opt-item"><span data-opt="favorite">收藏</span></a>';
    $html .= '</div>';
    $html .= '</div>';
    $html .= '</section>';
    
    echo $html;
}


/**
 * 分页函数
 */
function el_paging($ajax = false, $echo = true)
{

    if (is_singular()) {
        return;
    }

    global $wp_query, $paged;
    $max_page = $wp_query->max_num_pages;
    if ($max_page == 1) {
        return;
    }

    $ajax = _opz('paging_ajax_s', false);
    if ($ajax) {
        //ias自动加载
        $nex = _opz("ajax_trigger", '加载更多');
        //  add_filter('next_posts_link_attributes', 'el_next_posts_link_attributes_add_ias_class');
        $next_posts_link = get_next_posts_link($nex);
        if (!$next_posts_link) {
            return;
        }

        $ias_max = (int) _opz('ias_max', 3);
        $ias = (_opz('paging_ajax_ias_s', true) && ($paged <= $ias_max || !$ias_max)) ? ' class="next-page ajax-next lazyload" lazyload-action="ias"' : '  class="next-page ajax-next"';

        $pag_html = $next_posts_link ? '<div class="text-center theme-pagination ajax-pag"><div' . $ias . '>' . $next_posts_link . '</div></div>' : '';
    } else {
        $args = array(
            'prev_text' => '<i class="fa fa-angle-left em12"></i><span class="hide-sm ml6"> 上一页</span>',
            'next_text' => '<span class="hide-sm mr6">下一页 </span><i class="fa fa-angle-right em12"></i>',
            'type' => 'array',
        );
        $array = paginate_links($args);
        if (!$array) {
            return;
        }

        $pag_html = '<div class="pagenav ajax-pag">';
        $pag_html .= implode("", $array);
        $pag_html .= '</div>';
    }
    if ($echo) {
        echo $pag_html;
    } else {
        return $pag_html;
    }
}


function el_posts_mini_while($args = array())
{
    $defaults = array(
        'echo' => true,
    );

    $args = wp_parse_args((array) $args, $defaults);
    $get_permalink = get_permalink();

    global $post;

    $title = '<a href="' . $get_permalink . '" target="_blank" class=" "><div class="h-1x">' . get_the_title() . '</div> </a>';


    $html = '<li>';
    $html .= $title;
    $html .= '</li>';
    if ($args['echo']) {
        echo $html;
    } else {
        return $html;
    }
}